package com.dylan.历史.多线程.并发编程的艺术;

import com.dylan.历史.util.LogUtil;
import com.dylan.历史.util.SleepUtils;

import java.util.concurrent.CountDownLatch;

/**
 * Created by Dylan on 2018/9/19.
 *
 * CountDownLatch 内部是用同步器共享式同步状态来实现的
 * countDown()释放共享式同步状态，每调用一次同步状态就减少1，直到为0
 * await()获取共享式同步状态，如果共享状态不为0，则获取同步状态失败，进入同步队列，直到共享状态为0才会被唤醒
 */
public class CountDownLatchTest {

    private static CountDownLatch countDownLatch;

    public static void main(String[] args) {
        int count = 3;
        countDownLatch = new CountDownLatch(3);
        for (int i = 0; i < 5; i++) {
            new Thread(new Consumer()).start();
        }
        for (int i = 0; i < count; i++) {
            SleepUtils.seconds(1);
            new Thread(new Producer()).start();
        }
    }

    private static class Producer implements Runnable {
        @Override
        public void run() {
            LogUtil.info("我生产好了");
            countDownLatch.countDown();
        }
    }

    private static class Consumer implements Runnable {
        @Override
        public void run() {
            try {
                countDownLatch.await();
                LogUtil.info("我来消费了");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
